﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Drawing;

namespace XFControls.XFPanels.XFPanelItems
{
    public class XFItemAnimation : IXFItem
    {
        private int _height;
        private int _x;
        private int _y;
        private int _currFrame;
        private int _frameWidth;
        private int _numbFrames;
        private bool _alpha;

        #region IXFItem Members

        public XFPanelBase Parent { get; set; }
        public XFItemState State { get; set; }
        public Bitmap Buffer { get; set; }
        public Bitmap StoryLine { get; set; }
        public XFItemStyle Style { get; set; }
        public XFItemType ItemType { get; set; }

        public XFItemAnimation(int height, int x, int y)
        {
            _height = height;
            _x = x;
            _y = y;
            _currFrame = 0;
            ItemType = XFItemType.Display;
        }

        public int GetHeight()
        {
            return _height;
        }

        public void ResetHeight() { }

        public void ItemPaint(Graphics g, int x, int y)
        {
            if (StoryLine == null)
                return;

            //Calculate the left location of the drawing frame
            int XLocation = _currFrame++ * _frameWidth;
            if (_currFrame == _numbFrames)
                _currFrame = 0;

            Rectangle rect = new Rectangle(XLocation, 0, _frameWidth, StoryLine.Height);

            //Draw image
            if (_alpha)
                XFControls.XFControlUtils.DrawAlphaFirstPix(g, StoryLine, _x, _y, _frameWidth, StoryLine.Height, XLocation);
            else
                g.DrawImage(StoryLine, _x, _y, rect, GraphicsUnit.Pixel);
        }

        public XFItemClickResult GetClickResult()
        {
            return XFItemClickResult.Nothing;
        }

        public void SetStoryLine(string path, int frames)
        {
            _numbFrames = frames;
            try
            {
                StoryLine = new Bitmap(path);
                _frameWidth = StoryLine.Width / frames;


                var file = path.Split('\\').Last();
                _alpha = file.Contains("alpha");
            }
            catch (Exception e)
            {
            }
        }
        #endregion

        #region IDisposable Members

        public void Dispose()
        {
            if (Buffer != null)
                Buffer.Dispose();

            if (StoryLine != null)
                StoryLine.Dispose();
        }

        #endregion
    }
}
